import { IMenuNode } from "@/modules/management/menu";
import { RouteMeta, RouteRecordRaw, RouteRecordRedirectOption } from "vue-router";



export const routeFilter = (routes: RouteRecordRaw[], menuNode: IMenuNode[]) => {
  const appRoutes:RouteRecordRaw[] = []
  // 循环到了最低一级路由
  if(!routes) return
  // 添加双层循环，对比每一级路由 
  routes.forEach((route: RouteRecordRaw) => {
    menuNode.forEach((node: IMenuNode) => {
      if(route.name === node.node_route) {
        const { children, ...restRoute } = route
        const rest  = Object.assign({}, restRoute) as RouteRecordRaw
        // 含有子路由的路由
        if(Object.hasOwn(route, 'children')) {
          const nodeChildren = node.children as IMenuNode[]
          const result = routeFilter(children as RouteRecordRaw[], nodeChildren) as RouteRecordRaw[]
          rest.children = result
          // 一级路由，需要重新设置重定向
          if(Object.hasOwn(route.meta as RouteMeta , 'order')) {
            const temp = result[0].children as RouteRecordRaw[]
            const redirect = result[0].meta!.href ? result[0].meta!.href : temp[0].meta!.href
            rest.meta!.icon = node.node_icon_unselected
            rest.meta!.pickIcon = node.node_icon_selected
            rest.redirect = redirect as RouteRecordRedirectOption
          }
        }
        appRoutes.push(rest)
      }
    });
  });
  return appRoutes
}